package com.kuangstudy.controller.zset.taobao;

import com.kuangstudy.entity.Content;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: xuke
 * @time: 2021/6/9 21:25
 */
@RestController
@Slf4j
public class TaobaoOnlineRoomController {

    @Autowired
    private RedisTemplate redisTemplate;

    // 第一次进入房间，返回最新的5条弹幕
    @GetMapping("/goroom")
    public List<Content> initRoomData(Integer roomid, Integer userId) {
        List<Content> contentList = new ArrayList<>();
        String key = "room:" + roomid;

        // 进入房间后，返回最新的5条弹幕
        Set<ZSetOperations.TypedTuple<Content>> ranges = this.redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, 5);
        for (ZSetOperations.TypedTuple<Content> range : ranges) {
            contentList.add(range.getValue());
            log.info("content:{},score:{}", range.getValue(), range.getScore());
        }

        // 保存当前用户第一次访问拉取数据的时间，让下次拉取做为时间的起点
        long now = System.currentTimeMillis() / 1000;
        this.redisTemplate.opsForValue().set("user:room:time:" + userId, now);

        return contentList;
    }

    //进入房间后，客户端间隔5秒钟来拉取数据
    @GetMapping("/conentList")
    public List<Content> getConentList(Integer roomid, Integer userId) {
        List<Content> contentList = new ArrayList<>();
        String key = "room:" + roomid;
        String userkey = "user:room:time:" + userId;

        // 当前的时间
        long now = System.currentTimeMillis() / 1000;
        // 获取用户上次读取的时间
        long ago = Long.parseLong(this.redisTemplate.opsForValue().get(userkey).toString());
        log.info("查找弹幕的范围是：{},{}", ago, now);

        // 读取上次到现在的数据
        Set<ZSetOperations.TypedTuple<Content>> contentSets = this.redisTemplate.opsForZSet().rangeByScoreWithScores(key, ago, now);
        for (ZSetOperations.TypedTuple<Content> range : contentSets) {
            contentList.add(range.getValue());
            log.info("content:{},score:{}", range.getValue(), range.getScore());
        }

        // 保存当前用户访问拉取数据的时间，让下次拉取做为时间的起点
        this.redisTemplate.opsForValue().set("user:room:time:" + userId, now);
        return contentList;
    }


    // 下播以后
    @PostMapping("/levearoom")
    public String levearoom(Integer roomid) {
        // 保存当前用户访问拉取数据的时间，让下次拉取做为时间的起点
        this.redisTemplate.expire("room:" + 100, 10, TimeUnit.SECONDS);
        log.info("下播了，数据进行清理!!!");
        return "ok";
    }

}
